package cron.core.scheduler.trigger;

import cron.task.plugin.Task;

import java.util.Date;

/**
 * @author : willian fu
 * @version : 1.0
 * @date : 2021/3/9 0009 09:51
 */
public class FixedRateTrigger extends AbstractTrigger {

    //频率 ms
    private long rate;


    public FixedRateTrigger(long rate, Task worker) {
        this.rate = rate;
        this.worker = worker;
    }

    @Override
    public Date getNextTime() {
        long now = System.currentTimeMillis() / UNIT;
        if (null == nextTime){
            nextTime = new Date((now + rate) * UNIT);
        }else {
            long time = nextTime.getTime();
            do {
                time = time + rate * UNIT;
            }while (now > time);
            nextTime = new Date(time);
        }
        //System.err.println(DateUtil.toStr(new Date(now * UNIT)) + "  " + DateUtil.toStr(nextTime));
        return nextTime;
    }

    @Override
    public boolean isBeTrigger(long count) {
        return this.count <= count;
    }

    @Override
    public void updateRule(Object rule) {
        this.rate = Long.parseLong(rule.toString());
        toNext();
    }

    @Override
    public void run() {
        if (enable){
            worker.doRun();
        }
        super.run();
    }
}
